﻿using System;
using System.Collections.Specialized;
using System.IO;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using VitCode.BaseDataPageCreator.Setting;
using VitCode.Castle.DataAccess;
using VitCode.ObjectResolutionHelper;
using VitCode.Web.UI;

namespace VitCode.BaseDataPageCreator
{
    /// <summary>
    /// 面页控件创建附助类
    /// </summary>
    public class CreateControlHelper
    {
        private int iStartIndex;

        public string ReturnQueryStringValue(string keyString, Page p)
        {
            string strValue = p.Request.QueryString[keyString];
            if (strValue == null)
                strValue = "";
            return Convert.ToString(strValue);
        }

        /// <summary>
        /// 根据PgList的列名创建查询条件于DorpDownList
        /// </summary>
        /// <param name="pg">列表控件对象</param>
        /// <param name="ddlCondition">简单查询下拉框</param>
        public void SetDdlCondition(PaginationGrid pg, DropDownList ddlCondition)
        {
            SetDdlCondition(pg, ddlCondition, 0);
        }

        /// <summary>
        /// 设置指定的控件及子控件不可用
        /// </summary>
        /// <param name="c">控件</param>
        /// <param name="ctlHeadString">控件ID起始字符串约束</param>
        public static void SetControlDisabled(Control c,string ctlHeadString)
        {
            ControlCollection cc = c.Controls;
            if (cc != null && cc.Count > 0)
            {
                foreach (Control ic in cc)
                {
                    if (ic != null &&((String.IsNullOrEmpty(ctlHeadString)) || ic.ClientID != null && ic.ClientID.IndexOf(ctlHeadString) > -1))
                    {
                        if (ic.GetType() == typeof(ImageButton))
                            ic.Visible = false;
                        else
                        {
                            PropertyInfo pi = ic.GetType().GetProperty("Enabled");
                            if (pi != null)
                                pi.SetValue(ic, false, null);
                        }
                    }
                    SetControlDisabled(ic,ctlHeadString);
                }
            }
        }

        /// <summary>
        /// 设置控件为不可用
        /// </summary>
        /// <param name="c">控件对象</param>
        public static void SetControlDisabled(Control c)
        {
            SetControlDisabled(c, "");
        }

        /// <summary>
        /// 设置页面上动态加载的控件不可能
        /// </summary>
        /// <param name="page">页面对象</param>
        public void SetPageControlsDisabled(Page page)
        {
            ControlCollection cc = page.Controls;
            foreach (Control c in cc)
            {
                SetControlDisabled(c, BaseDataKeyInfo.OBJ_PRO_HEAD_STRING);
            }
        }

        /// <summary>
        /// 为返回的ErrorMessage进行解析,以对象Memo进行描述
        /// </summary>
        /// <param name="str"></param>
        public void SetDeleteErrMsgEachClassMemo(ref string str)
        {
            string strFG = BaseDataAccess.ERR_OBJ_NAME_FG;
            int iFrom = str.IndexOf(strFG, iStartIndex);
            if (iFrom > -1)
            {
                iStartIndex = iFrom + strFG.Length;
                int iEnd = str.IndexOf(strFG, iStartIndex);
                if (iEnd >= iStartIndex)
                {
                    iStartIndex = iEnd + strFG.Length;
                    string strClassName = str.Substring(iFrom + strFG.Length, iEnd - iFrom - strFG.Length);
                    var xmlReader = new ObjXmlReader(AppDomain.CurrentDomain.BaseDirectory + "Setting\\BaseDataSet.xml");
                    string strClassMemo = "";
                    strClassMemo = strClassName == "WoCommand" ? "工單命令" : xmlReader.GetNodeAttributeValue(strClassName, "Memo");
                    str = str.Replace(strFG + strClassName + strFG, strClassMemo);
                }
                SetDeleteErrMsgEachClassMemo(ref str);
            }
            else
                iStartIndex = 0;
        }

        public void SetDeleteErrMsg(ref string str)
        {
            SetDeleteErrMsgEachClassMemo(ref str);
        }

        /// <summary>
        /// 向WEB客户端推送文件
        /// </summary>
        /// <param name="filePath">源文件路径</param>
        /// <param name="clientFileName">推送至客户端时显示的文件名称</param>
        public void DownloadFile(string filePath, string clientFileName)
        {
            HttpResponse Response = HttpContext.Current.Response;
            Response.Clear();
            Response.Charset = "GB2312";
            Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(clientFileName));
            Response.ContentEncoding = Encoding.Default;
            Response.ContentType = "application/ms-excel";

            var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
            if (stream.Length > 10000000)
            {
                Response.AddHeader("Content-Length", stream.Length.ToString());
                var readbuffer = new byte[10000];
                int readlength = 0;
                try
                {
                    if (stream.Length > 0)
                    {
                        do
                        {
                            readbuffer.Initialize();
                            readlength = stream.Read(readbuffer, 0, readbuffer.Length);
                            Response.OutputStream.Write(readbuffer, 0, readlength);
                            Response.OutputStream.Flush();
                        } while (readlength > 0 && Response.IsClientConnected);
                        Response.End();
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception("檔下載失敗！" + ex.Message);
                }
                finally
                {
                    stream.Close();
                }
            }
            else
            {
                stream.Close();
                Response.WriteFile(filePath); //此方法發現在下載檔時，會把網頁本身的內容一併下載並附加在檔後。停止使用。
                Response.End();
            }
        }

        /// <summary>
        /// 检测是否为正数
        /// </summary>
        /// <param name="field"></param>
        /// <returns></returns>
        public static bool CheckIsInt(string field)
        {
            string strGroundTotal = Convert.ToString(field).Trim();
            if (strGroundTotal.Length == 0 || !Regex.IsMatch(strGroundTotal, @"^[+-]?\d*$"))
            {
                return false;
            }
            return true;
        }

        /// <summary>
        /// 检测是否为正小数
        /// </summary>
        /// <param name="field"></param>
        /// <param name="fieldname"></param>
        /// <param name="Message"></param>
        /// <returns></returns>
        public static bool CheckIsPlusDouble(string field, string fieldname, out string Message)
        {
            Message = null;
            string strGroundTotal = Convert.ToString(field).Trim();
            if (!Regex.IsMatch(strGroundTotal, @"^[+]?\d*[.]?\d*$"))
            {
                Message = fieldname + "必須為非負小數";
                return false;
            }
            return true;
        }

        /// <summary>
        /// 根据PgList的列名创建查询条件于DorpDownList
        /// </summary>
        /// <param name="pg">列表控件对象</param>
        /// <param name="ddlGroupPro">简单查询下拉框</param>
        /// <param name="selectedIndex">加载完下拉框默认的选择的项索引</param>
        public void SetDdlCondition(PaginationGrid pg, DropDownList ddlGroupPro,int selectedIndex )
        {
            ddlGroupPro.Items.Clear();
            for (int i = 0; i < pg.Columns.Count; i++)
            {
                if (pg.Columns[i] is PaginationGridBoundColumn)
                {
                    var bColumn = (PaginationGridBoundColumn)pg.Columns[i];
                    ddlGroupPro.Items.Add(new ListItem(bColumn.HeaderText, bColumn.DataField));
                }
            }
            ddlGroupPro.SelectedIndex = selectedIndex;
        }
    }
}
